package com.shopping.auth.controller;

import com.alibaba.fastjson.JSON;
import com.shopping.auth.feign.MemberFeignService;
import com.shopping.auth.feign.ThirdPartFeignService;
import com.shopping.auth.vo.UserLoginVo;
import com.shopping.auth.vo.UserRegisterVo;
import com.shopping.common.constant.AuthServerConstant;
import com.shopping.common.exception.BizCodeEnum;
import com.shopping.common.utils.R;
import com.shopping.common.vo.MemberRespVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author Europa
 */
@Controller
public class LoginController {

    @Resource
    private ThirdPartFeignService thirdPartFeignService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    MemberFeignService memberFeignService;

    @RequestMapping("/login.html")
    public String login(HttpSession session) {
        Object attribute = session.getAttribute(AuthServerConstant.LOGIN_USER);
        return (Objects.nonNull(attribute)) ? "redirect:http://shopping.com" : "login";
    }


    /**
     * 发送验证码
     *
     * @param phone 用户手机号
     * @return
     */
    @ResponseBody
    @PostMapping("/sms/sendcode")
    public R sendCode(@RequestParam("phone") String phone) {
        String authPhone = AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone;
        String redisCacheCode = stringRedisTemplate.opsForValue().get(authPhone);
        if (!StringUtils.isEmpty(redisCacheCode)) {
            return R.error(BizCodeEnum.SMS_CODE_EXCEPTION.getCode(), BizCodeEnum.SMS_CODE_EXCEPTION.getMsg());
        }
        double random = Math.random();
        String code = String.valueOf(random).substring(2, 8);
        stringRedisTemplate.opsForValue().set(authPhone, code, 60, TimeUnit.SECONDS);
        try {
            thirdPartFeignService.sendCode(phone, code);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.ok();
    }

    /**
     * 账号注册
     *
     * @param registerVo
     * @param result
     * @param redirectAttributes RedirectAttributes,重定向不会带走request的数据,这个可以.
     *                           原理是放入session中,分布式下可能会有问题
     * @return
     */
    @PostMapping("/register")
    public String register(@Valid UserRegisterVo registerVo,
                           BindingResult result,
                           RedirectAttributes redirectAttributes) {
        if (result.hasErrors()) {
            Map<String, String> error = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField,
                    fieldError -> {
                        if (fieldError.getDefaultMessage() != null) {
                            return fieldError.getDefaultMessage();
                        }
                        return "";
                    })
            );
            redirectAttributes.addFlashAttribute("error", error);
            return "redirect:http://auth.shopping.com/register.html";
        }
        String code = registerVo.getCode();
        String authPhone = AuthServerConstant.SMS_CODE_CACHE_PREFIX + registerVo.getPhone();
        String cachePhone = stringRedisTemplate.opsForValue().get(authPhone);
        //判断缓存中是否存在验证码
        if (StringUtils.isEmpty(cachePhone)) {
            HashMap<String, String> error = new HashMap<>(16);
            error.put("code", "验证码错误");
            redirectAttributes.addFlashAttribute("error", error);
            return "redirect:http://auth.shopping.com/register.html";
        }
        //验证通过,删除缓存,注册用户
        if (cachePhone.equals(code)) {
            stringRedisTemplate.delete(authPhone);
            R r = memberFeignService.register(registerVo);
            if (r.getCode() == 0) {
                return "redirect:http://auth.shopping.com/login.html";
            } else {
                HashMap<String, String> error = new HashMap<>(16);
                error.put("msg", "用户名或手机已存在");
                redirectAttributes.addFlashAttribute("error", error);
                return "redirect:http://auth.shopping.com/register.html";
            }
        } else {
            HashMap<String, String> error = new HashMap<>(16);
            error.put("code", "验证码错误");
            redirectAttributes.addFlashAttribute("error", error);
            return "redirect:http://auth.shopping.com/register.html";
        }
    }

    @PostMapping("/login")
    public String login(UserLoginVo loginVo,
                        RedirectAttributes redirectAttributes,
                        HttpSession session) {
        R login = memberFeignService.login(loginVo);
        if (login.getCode() != 0) {
            HashMap<String, String> error = new HashMap<>(16);
            error.put("msg", "账号或密码错误");
            redirectAttributes.addFlashAttribute("error", error);
            return "redirect:http://auth.shopping.com/login.html";
        }
        String json = (String) login.get("msg");
        MemberRespVo memberRespVo = JSON.parseObject(json, MemberRespVo.class);
        session.setAttribute(AuthServerConstant.LOGIN_USER, memberRespVo);
        return "redirect:http://www.shopping.com";
    }


}
